package cn.kiliter.dao;

import cn.kiliter.model.User;
import cn.kiliter.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());

    public void addUser(User user) throws SQLException {
        String sql = "insert into user";
        sql += " (username,PASSWORD,gender,email,telephone,introduce,activeCode,state,role,registTime)";
        sql += " values(?,?,?,?,?,?,?,?,?,?)";
        List<Object> list=new ArrayList<>();
        list.add(user.getUsername());
        list.add(user.getPassword());
        list.add(user.getGender());
        list.add(user.getEmail());
        list.add(user.getTelephone());
        list.add(user.getIntroduce());
        list.add(user.getActiveCode());
        list.add(user.getState());
        list.add(user.getRole());
        list.add(user.getRegistTime());
        qr.update(sql,list.toArray());
    }
    public User findUserByactiveCode( String  activecode) throws SQLException {
        User user=null;
        String sql="select * from user where activeCode = ?";
        user=qr.query(sql,new BeanHandler<User>(User.class),activecode);
        return user;
    }

    public void updateState(String activecode) throws SQLException {
        String sql="update user set state =1 where activeCode=? ";
        qr.update(sql,activecode);
    }

    public User findUserByUserAndPassword(User login) throws SQLException {
        String sql="select * from user where username = ? and password = ?";
        return qr.query(sql,new BeanHandler<User>(User.class),login.getUsername(),login.getPassword());
    }

    public User findById(int id) throws SQLException {
        String sql="select * from user where id = ? ";
        return qr.query(sql,new BeanHandler<User>(User.class),id);
    }

    public void updateByUser(User user) throws SQLException {
        String sql="update user set password=? , gender =? , telephone =? where id=? ";
        qr.update(sql,user.getPassword(),user.getGender(),user.getTelephone(),user.getId());
    }
}
